// pages/mine/joinMerchant/joinMerchant.js
const areaJson = require('../../../utils/areaJson/area.js');
import Toast from '../../../miniprogram/miniprogram_npm/vant-weapp/toast/toast';
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    merchantInfo:{
      showNumber:false,
      sessionKey:'',
      name:'',
      accountMobile:'',
      province: '省',
      city: '市',
      area: '区',
      address:'',
      selectFirstId:'',//选择的一级分类id
      selectSecondId:'',//选择的二级分类id
      selectFirstName:'请选择一级商户分类',//选择的一级分类名
      selectSecondName:'请选择二级商户分类',//选择的二级分类名
      latitude:'',
      longitude:'',
    },
    areaShow: false,//省市区弹框
    areaList: areaJson.area,//省市区数据，在area.josn获取
    
    isPartner1:false,//一级分类弹框是否显示
    isPartner2:false,//二级分类弹框是否显示

    categoryList1:[],//前端所展示的只有名字的一级分类列表
    categoryList2:[],//前端所展示的只有名字的二级分类列表
    list1:[],// 后台返回一级分类列表
    list2:[],// 后台返回二级分类列表

    upid: '',//推荐人id
    upname: '',//推荐人name
    centreId: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (event) {
    console.log(event)
    let scene = event.scene;
    if(scene){//根据小程序码进入
      let tt = scene.split('-');
      let obj = {};
      tt.forEach(item=>{
        obj[item.split('!')[0]] = item.split('!')[1];
      })
      console.log(obj)
      this.setData({
        upid: obj.uid || '',
      })
    } else {
      this.setData({
        upid: event.upid || '',
        upname: event.upname || '',
      })
    }

    this.getClassifyList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let user = app.getUser();
    if(user.id == null) wx.navigateTo({
      url: '/pages/login/login'
    })
  },
  // 查询用户申请信息
  getApplyInfo:function(){
    let that = this;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/center/info',
      data: {
        mid:app.getUser().id
      },
    }).then(res =>{
      if(res.data.data){
        let data = res.data.data;
        that.data.centreId = data.centreId;
        that.data.merchantInfo.name = data.name;
        that.data.merchantInfo.accountMobile = data.accountMobile;
        that.data.merchantInfo.province = data.province;
        that.data.merchantInfo.city = data.city;
        that.data.merchantInfo.area = data.area;
        that.data.merchantInfo.address = data.address;
        that.data.merchantInfo.latitude = data.lat;
        that.data.merchantInfo.longitude = data.lon;
        that.data.merchantInfo.selectFirstId = data.pcate;
        that.data.merchantInfo.selectSecondId = data.ccate;
        console.log(that.data.list1);
        that.data.list1.forEach(item =>{
          console.log(item.id);
          if(that.data.merchantInfo.selectFirstId == item.id){
            that.data.merchantInfo.selectFirstName = item.name;
            item.categoryList.forEach(secondItem =>{
              if(that.data.merchantInfo.selectSecondId == secondItem.id){
                that.data.merchantInfo.selectSecondName = secondItem.name;
              }
            })
          }
        });
        that.setData({
          merchantInfo: that.data.merchantInfo,
        })
      }else{
        // 缓存里面取值
        let info = wx.getStorageSync('merchantInfo')
        if(info){
          info = JSON.parse(info);
          that.data.merchantInfo.name = info.name;
          that.data.merchantInfo.accountMobile = info.accountMobile;
          that.data.merchantInfo.province = info.province;
          that.data.merchantInfo.city = info.city;
          that.data.merchantInfo.area = info.area;
          that.data.merchantInfo.address = info.address;
          that.data.merchantInfo.latitude = info.latitude;
          that.data.merchantInfo.longitude = info.longitude;
          that.data.merchantInfo.selectFirstId = info.selectFirstId;
          that.data.merchantInfo.selectSecondId = info.selectSecondId;
          that.data.merchantInfo.selectFirstName = info.selectFirstName;
          that.data.merchantInfo.selectSecondName = info.selectSecondName;
          that.setData({
            merchantInfo:that.data.merchantInfo
          })
        }
      }
    })
  },
  // 获取分类信息
  getClassifyList:function(){
    let _this = this;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/centre/subject',
      data: {
        
      },
    }).then(res =>{
      let rows = res.data.data;
      rows.forEach(item =>{
        _this.data.categoryList1.push(item.name)
      });
      _this.setData({
        categoryList1:_this.data.categoryList1,
        list1:rows,
      });
      this.getApplyInfo();
    })
  },
  onChangeName:function(event){
    let name = 'merchantInfo.name';
    this.setData({
      [name]: event.detail
    })
  },
  onChangeMobile:function(event){
    let accountMobile = 'merchantInfo.accountMobile';
    this.setData({
      [accountMobile]: event.detail
    })
  },
  onChangeAddress:function(event){
    // let address = 'merchantInfo.address';
    // this.setData({
    //   [address]: event.detail
    // })
    console.log(1);
  },
  call_map:function(){
    let _this = this;
    wx.getLocation({////获取当前位置信息
      type: 'wgs84',
      //获取位置成功
      success: function (res) {
        console.log(res)  //获取的的当前位置的详细信息
        wx.chooseLocation({////选择位置
          success: function (res) {
            console.log(res);
            let address = 'merchantInfo.address';
            let latitude = 'merchantInfo.latitude';
            let longitude = 'merchantInfo.longitude';
            _this.setData({
              [address]: res.name,
              [latitude]: res.latitude,
              [longitude]: res.longitude,
            });
          }
        })
      },
      //获取位置失败
      fail: function (err) {
        console.log("拒绝访问地址权限")
      },
      //接口调用结束的回调函数（调用成功、失败都会执行）
      complete: function (info) {
        console.log("完成")
      },
    })
  },
  //省市区确定
  areaConfirm(event){
    let _this = this;
    _this.areaMonitor();
    let province = 'merchantInfo.province';
    let city = 'merchantInfo.city';
    let area = 'merchantInfo.area';
    _this.setData({
      [province]: event.detail.values[0].name,
      [city]: event.detail.values[1].name,
      [area]: event.detail.values[2].name,
    })
  },

  //省市区弹框
  areaMonitor(){
    let _this = this;
    _this.setData({
      areaShow: !_this.data.areaShow
    })
  },

  //一级分类确认
  partnerConfirm1(event){
    let _this = this;
    let index = event.detail.index;
    let selectFirstId = 'merchantInfo.selectFirstId';
    let selectFirstName = 'merchantInfo.selectFirstName';
    _this.setData({
      list2:_this.data.list1[index].categoryList,
      [selectFirstId]:_this.data.list1[index].id,
      [selectFirstName]:event.detail.value
    });
    _this.data.list2.forEach(item =>{
      _this.data.categoryList2.push(item.name)
    });
    _this.setData({
      categoryList2:_this.data.categoryList2
    });
    _this.isPartnerMonitor1();
  },
  isPartnerMonitor1(){
    let _this = this;
    _this.setData({
      isPartner1: !_this.data.isPartner1
    })
  },
  // 二级分类确认
  partnerConfirm2(event){
    let _this = this;
    let index = event.detail.index;
    let selectSecondId = 'merchantInfo.selectSecondId';
    let selectSecondName = 'merchantInfo.selectSecondName';
    _this.setData({
      [selectSecondId]:_this.data.list2[index].id,
      [selectSecondName]:event.detail.value
    });
    _this.isPartnerMonitor2();
  },
  isPartnerMonitor2(){
    let _this = this;
    _this.setData({
      isPartner2: !_this.data.isPartner2
    })
  },
  jumpMerchantTwo:function(){
    let that = this;
    let user = app.getUser();
    let merchantInfo = that.data.merchantInfo;
    if(!merchantInfo.name){
      Toast('请填写店铺名称'); return;
    } else if (!merchantInfo.accountMobile || !(/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/.test(merchantInfo.accountMobile))) {
      Toast('请填写正确电话号码'); return;
    } else if (!(merchantInfo.province || merchantInfo.city || merchantInfo.area)) {
      Toast('请选择省市区'); return;
    } else if (!merchantInfo.address) {
      Toast('请填写详细地址'); return;
    } else if (!merchantInfo.selectFirstId){
      Toast('请选择一级分类'); return;
    } else {
      wx.setStorageSync('merchantInfo', JSON.stringify(merchantInfo));
      wx.navigateTo({
        url: 'merchantTwo/merchantTwo?upid=' + that.data.upid + '&upname=' + that.data.upname + '&centreId=' + that.data.centreId,
      })
    }
  },

  //登录
  toDoLogin(){
    let _this = this;
    wx.login({
      success: function (res) {
        var code = res.code;
        if (res.code) {
          wx.getUserInfo({
            success: function (res) {
              app.requestUrl({
                method: 'POST',
                url: '/wxapi/app/login',
                data: {
                  code: code,
                  centreId: app.globalData.loginCentreId,
                  flag: 1,
                },
                load: 1,
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },
              }).then((data)=>{
                if (data.data.success)
                  _this.wxUserInfo(res, data.data.data);
              });
            }
          })
        }
      }
    })
  },
  //得到用户信息
  wxUserInfo(res, encryptInfo) {
    let _this = this;
    let merchantInfo = _this.data.merchantInfo;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/app/sendXcxUnionId',
      data: {
        encryptedData: res.encryptedData,
        iv: res.iv,
        sessionKey: encryptInfo
      },
      load: 1,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
    }).then((data) => {
      //4.解密成功后 获取自己服务器返回的结果
      if (data.data.success) {

        let info = data.data.data;
        wx.setStorageSync('userInfo', JSON.stringify(info));//保存用户信息
        wx.setStorageSync('authToken', data.data.authToken);//保存身份验证
        wx.setStorageSync('merchantInfo', JSON.stringify(merchantInfo));
        _this.getUserInfo(data.data.data.id);
        if(info.mobile == ''){
          _this.setData({
            showNumber:true,
            sessionKey: encryptInfo,
          });
        }else{
          wx.navigateTo({
            url: 'merchantTwo/merchantTwo?upid=' + _this.data.upid + '&upname=' + _this.data.upname + '&centreId=' + _this.data.centreId,
          })
        };
      }
    })
  },
  //得到用户信息
  getUserInfo(id) {
    let _this = this;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/member',
      data: {
        id: id,
      },
    }).then((res) => {
      wx.setStorageSync('shopInfo', JSON.stringify(res.data.userShop));
    })
  },
  getPhoneNumber(e){
    let _this = this;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      app.requestUrl({
        method: 'POST',
        url: '/wxapi/getEncryptedUserInfo',
        data: {
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
          sessionKey: _this.data.sessionKey,
        },
        load: 0,
      }).then((data)=>{
        if (data.data.success){
          wx.navigateTo({
            url: 'merchantTwo/merchantTwo?upid=' + _this.data.upid + '&upname=' + _this.data.upname + '&centreId=' + _this.data.centreId,
          })
        }
          
      });
    }
    
  },
})